package com.tjmc.nsia.core.controller.front;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tjmc.nsia.core.constant.BusinessType;
import com.tjmc.nsia.core.dao.entity.NsiaMenu;
import com.tjmc.nsia.core.dao.entity.NsiaUser;
import com.tjmc.nsia.core.domain.AjaxResult;
import com.tjmc.nsia.core.domain.Log;
import com.tjmc.nsia.core.dto.req.LoginBody;
import com.tjmc.nsia.core.service.NsiaMenuService;
import com.tjmc.nsia.core.service.NsiaUserService;
import com.tjmc.nsia.core.service.ResourceService;
import com.tjmc.nsia.core.service.WxChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 用户信息表 控制器
 * </p>
 *
 * @author Luc
 * @date 2024/06/03
 */
@RestController
@RequestMapping("/user")
public class NsiaUserController {

    @Autowired
    private NsiaUserService nsiaUserService;

    @Autowired
    private WxChatService wxChatService;

    @Autowired
    private NsiaMenuService nsiaMenuService;

    @Autowired
    private ResourceService resourceService;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        SaTokenInfo tokenInfo = nsiaUserService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        return AjaxResult.success(tokenInfo);
    }

    @GetMapping(value = {"/getInfo", "/profile"})
    public AjaxResult getInfo() {
        Map<String, Object> data = new HashMap<String, Object>() {{
            put("user", nsiaUserService.getLoginUser());
            put("menus", nsiaMenuService.list(new QueryWrapper<NsiaMenu>().eq("level", 2)));
        }};
        return AjaxResult.success(data);
    }

    @PostMapping("/logout")
    public AjaxResult logout() {
        nsiaUserService.logout();
        return AjaxResult.success();
    }

    @Log(title = "更新个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/profile")
    public AjaxResult updateProfile(@RequestBody NsiaUser user) {
        user.setId(nsiaUserService.getLoginUser().getId());
        user.setUsername(null);
        user.setPassword(null);
        user.setOpenid(null);
        if(nsiaUserService.updateById(user)) {
            return AjaxResult.success();
        }
        return AjaxResult.error("修改个人信息异常，请联系管理员！");
    }

    @Log(title = "修改密码", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(@RequestParam("password") String password) {
        NsiaUser user = nsiaUserService.getLoginUser();
        if(!Objects.isNull(user)) {
            user.setPassword(DigestUtil.md5Hex(password.trim()));
            user.setUpdateTime(LocalDateTime.now());
            if(nsiaUserService.updateById(user)) {
                return AjaxResult.success();
            }
        }
        return AjaxResult.error("修改密码异常，请联系管理员！");
    }


    @Log(title = "更新Session", businessType = BusinessType.UPDATE)
    @GetMapping(value = {"/refreshSession"})
    public AjaxResult refreshSession() {
        Integer newSessionId = nsiaUserService.refreshSession(StpUtil.getLoginIdAsLong());
        if(!Objects.isNull(newSessionId) && newSessionId >= 0) {
            return AjaxResult.success(newSessionId);
        }
        return AjaxResult.error();
    }

    @GetMapping(value = {"/getChatSessions"})
    public AjaxResult getChatSessions() {
        return AjaxResult.success(nsiaUserService.getChatSessions(StpUtil.getLoginIdAsLong()));
    }

    @GetMapping(value = {"/clearSessions"})
    public AjaxResult clearSessions() {
        nsiaUserService.clearSessions(StpUtil.getLoginIdAsLong());
        return AjaxResult.success();
    }

    @PostMapping("/wxLogin")
    public AjaxResult wxLogin(@RequestParam("code") String code) {
        JSONObject response = wxChatService.jscode2session(code);
        if(!Objects.isNull(response)) {
            String openid = response.getString("openid");
            String sessionKey = response.getString("session_key");
            if(StringUtils.hasText(openid) && StringUtils.hasText(sessionKey)) {
                SaTokenInfo tokenInfo = nsiaUserService.wxLogin(openid, sessionKey);
                return AjaxResult.success(tokenInfo);
            } else {
                return AjaxResult.error("openid 或 sessionKey 为空");
            }
        }
        return AjaxResult.error("jscode2session 响应为空");
    }

    @PostMapping("/uploadAvatar")
    public String uploadAvatar(@RequestParam("file") MultipartFile file) {
        String path = resourceService.uploadFile(file);
        NsiaUser nsiaUser = nsiaUserService.getLoginUser();
        nsiaUser.setAvatar(path);
        nsiaUser.setUpdateTime(LocalDateTime.now());
        nsiaUserService.updateById(nsiaUser);
        return path;
    }
}
